<!--
 * @Description: 选择农场页面
-->
<template>
  <div class="choose-company">
    <Header />
    <div class="main-content">
      <el-scrollbar wrap-class="scrollbar-wrapper">
        <div class="slidebar">
          <div class="list">
            <div v-for="(item, index) in list" :key="index" class="item" :class="activeIdx === index ? 'active' : ''"
              @click="changeActiveIdx(index, item)">
              {{ item }}
            </div>
          </div>
        </div>
      </el-scrollbar>
      <div class="main">
        <div class="content">
          <!-- 选农场 -->
          <div v-if="selectstau === 2" class="farm-list">
            <div v-for="(item, ind) in farmList" :key="ind" class="farm-item">
              <div class="title">{{ item.organizationName }}</div>
              <div class="loc">
                <i class="el-icon-location"></i>
                <div class="addr">{{ item.address }}</div>
              </div>
              <div class="pic"
                @click="goToTheFarm(item.organizationId, item.organizationMark, item.parentId, item.organizationName, item.isTenant)">
              </div>
              <div class="child-farm" @click="selectfarmchild(item)">选择下级</div>
            </div>
          </div>
        </div>
        <Footer />
      </div>
    </div>
    <!-- 首先选择公司的弹框 -->
    <div v-if="selectstau === 1" class="first-tankuang">
      <!-- 选顶级组织结构 -->
      <div class="org-list">
        <div class="org-title">
          <div class="sel-te">选择公司</div>
        </div>
        <div class="search">
          <input placeholder="请输入公司名称" class="search-input" />
          <div class="search-button">查询</div>
        </div>
        <div class="company-list">
          <div v-for="item in organizationList" :key="item.companyId" class="sel-company"
            @click="goToselectFarm(item.companyId)">
            {{ item.companyName }}
          </div>
        </div>
      </div>
    </div>
    <!-- 选择子农场弹框 -->
    <div v-if="ischildfarmstau" class="three-tankuang">
      <!-- 选顶级组织结构 -->
      <div class="org-list">
        <div class="childcompany-list">
          <div class="org-title">
            <div class="sel-te">选择下级</div>
          </div>
          <div class="select-main">
            <div class="far-sel">
              <el-cascader ref="myCascader" :options="childfarmlist" placeholder="请选择子基地"
                :props="{ checkStrictly: true, expandTrigger: 'hover', value: 'organizationId', children: 'child', label: 'organizationName' }"
                @change="cascaderChange" />
            </div>
            <div class="toindex-but" @click="lasttoindex()">
              确认
            </div>
            <div class="quxiao-but" @click="ischildfarmstau = false">
              取消
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Header from "@/layout/components/Header/index";
import Footer from "@/layout/components/Footer/index";
import userService from "@/api/user/index";
// import { getToken, setToken } from "@/utils/auth";
import store from "@/store";
// import permission from "@/store/modules/permission";
import { setToken } from "@/utils/auth";
export default {
  name: "ChoseCompany",
  components: { Header, Footer },
  data() {
    return {
      selectstau: 1, // 1为选择顶级组织结构，2为选择选择农场
      ischildfarmstau: false, // 展示子农场
      organizationList: [
      ], // 顶级组织结构列表
      activeIdx: "",
      search: "",
      farmList: [
        { organizationName: "星光农场", organizationId: 1 }
      ],
      // 星光农场下的组织
      // 被选择的id
      nowChildFarmSelectIdList: [],
      // 列表信息
      childfarmlist: [
        // { organizationName: "星光农场1", organizationId: 1,
        //   child: [
        //     { organizationName: "星光农场1-1",
        //       organizationId: 15,
        //       child: [
        //         { organizationName: "星光农场1-1", organizationId: 16 }
        //       ] },
        //     { organizationName: "星光农场1-1",
        //       organizationId: 16,
        //       child: [
        //         { organizationName: "星光农场1-1", organizationId: 16 }
        //       ] }
        //   ]
        // }
      ],
      // true 启用动态路由 false 启用静态路由
      // nowmenutype: permission.nowmenutype
      nowmenutype: false
    };
  },
  computed: {
    list() {
      let arr = [...Array(26).keys()].map(i => String.fromCharCode(i + 65));
      arr.unshift("#");
      return arr;
    }
  },
  watch: {},
  mounted() {
    this.tologin()
    // 查询农场
    this.getFarmList();
  },
  methods: {
    tologin() {
      let tr = this.$route.query;
      if (tr.account) {
        let loginForm = {
          account: decodeURIComponent(tr.account),
          password: tr.password
        }
        this.$router.push({ path: "/login", query: loginForm })
      }
    },
    // 获取顶级组织结构id
    getFarmList() {
      this.$router.push({ name: "selctBase" })
      // 获取顶级组织结构id,
      // userService.organizationTop().then(
      //   res => {
      //     this.organizationList = res.data
      //     if (res.length === 0 || res.data === []) {
      //       this.$message.warning("该账户下无公司，请联系管理员！")
      //       removeToken("token")
      //       this.$router.push({ path: "/login" })
      //     } else if (this.organizationList.length === 1) {
      //       this.goToselectFarm(this.organizationList[0].companyId)
      //     }
      //   }
      // )
    },
    // 点击组织结构触发方法
    goToselectFarm(e) {
      // 存储公司的companyId
      setToken("companyId", e)
      // 存储organizationMark
      // setToken("organizationMark", commark)
      // 获取databasename,并且存储
      this.getdataname(e)
      //  获取农场数据
      userService.farmListbyOrganizationId(e).then(
        res => {
          this.farmList = res.data
          if (this.farmList.length > 0) {
            this.$message.success("选择顶级组织结构成功！")
            this.selectstau = 2
          } else {
            this.$message.warning("选择顶级组织结构失败！")
          }
          if (this.farmList.length === 1) {
            // 判断有没有下级
            userService.gettreeslist(this.farmList[0].organizationId).then(
              // userService.farmListbyOrganizationId(this.farmList[0].organizationId).then(
              res => {
                let childlistone = res.data
                // this.childfarmlist = this.filterArrForKey(childlistone)
                if (childlistone[0].child.length === 0) {
                  // 存储承租户的parentid,当isTenant===true,settoken-parentid
                  if (childlistone[0].isTenant === true) {
                    setToken("parentId", childlistone[0].parentId)
                    // console.log(childlistone[0].parentId)
                  }
                  // 存储获取路由的所需的pid
                  setToken("routerpid", this.farmList[0].parentId)
                  // console.log(childlistone[0].parentId)
                  // console.log(childlistone[0])
                  // 存储其他的必要数据
                  setToken("organizationId", childlistone[0].organizationId);
                  setToken("organizationList", childlistone[0].organizationId)
                  setToken("organizationMark", childlistone[0].organizationMark)
                  if (childlistone[0].organizationName) {
                    setToken("organizationName", childlistone[0].organizationName)
                  }
                  // 让动态路由重新加载
                  if (this.nowmenutype) {
                    let accessRoutes = store.dispatch(
                      "permission/generateRoutes"
                    );
                    // console.log(11)
                    accessRoutes.then(res => {
                      // this.$router.push({ name: `${res[0].children[0].name}` });
                      this.$router.push({ name: "selctBase" });
                    })
                  } else {
                    this.$router.push({ name: "selctBase" });
                  }
                }
              }
            )
          }
        }
      )
    },
    // 点击农场:rouertpid用于获取菜单
    async goToTheFarm(organizationId, organizationMark, rouertpid, organizationName, isTenant) {
      // 存储顶级农场id
      setToken("organizationId", organizationId);
      setToken("organizationMark", organizationMark)
      if (organizationName) {
        setToken("organizationName", organizationName)
      }
      setToken("routerpid", rouertpid)
      // 存储承租户的parentid,当isTenant===true,settoken-parentid
      // ----
      if (isTenant) {
        // 判断有没有下级
        userService.gettreeslist(organizationId).then(
          // userService.farmListbyOrganizationId(this.farmList[0].organizationId).then(
          res => {
            let childlistone = res.data
            // this.childfarmlist = this.filterArrForKey(childlistone)
            setToken("parentId", childlistone[0].parentId)
          }
        )
      }
      // --------------
      // 存储所有组织结构字符串
      // console.log(rouertpid)
      let orgliststring = await this.getchildnodeidlist(organizationId)
      let orgidlisttwo
      if (orgliststring.length > 0) {
        orgidlisttwo = organizationId + ',' + orgliststring
      } else {
        orgidlisttwo = organizationId
      }
      setToken("organizationList", orgidlisttwo)
      // 让动态路由重新加载
      if (this.nowmenutype) {
        let accessRoutes = store.dispatch(
          "permission/generateRoutes"
        );
        // console.log(11)
        accessRoutes.then(res => {
          // this.$router.push({ name: `${res[0].children[0].name}` });
          this.$router.push({ name: "selctBase" });
        })
      } else {
        this.$router.push({ name: "selctBase" });
      }
    },
    // 点击选择子基地
    selectfarmchild(e) {
      this.ischildfarmstau = true
      // 第二层
      userService.gettreeslist(e.organizationId).then(
        res => {
          let childlistone = res.data
          this.childfarmlist = this.filterArrForKey(childlistone)
          this.ischildfarmstau = true
        }
      )
    },
    // 点击确认按钮
    async lasttoindex() {
      // 当前选中节点列表单选
      let orgidlistone = this.$refs.myCascader.getCheckedNodes()[0]
      // console.log(orgidlistone)
      if (!orgidlistone) {
        this.$message.warning("请基地下农场！")
        return
      }
      // 存储获取路由的所需的pid
      setToken("routerpid", orgidlistone.data.parentId)
      // console.log(orgidlistone.data.parentId)

      // 存储organizationMark
      let compmark = orgidlistone.data.organizationMark
      setToken("organizationMark", compmark)
      if (orgidlistone.data.organizationName) {
        setToken("organizationName", orgidlistone.data.organizationName)
      } else {
        setToken("organizationName", '')
      }
      // 选中的父idlist
      let parlist = orgidlistone.path
      // 是否还有子节点 true为有
      let hasChild = orgidlistone.hasChildren
      // 存储承租户的parentid,当isTenant===true,settoken-parentid
      if (orgidlistone.data.isTenant === true) {
        setToken("parentId", orgidlistone.data.parentId)
      }
      // 选中的id
      let nowselectid = orgidlistone.value
      setToken("organizationId", nowselectid)
      // 选中的所有层级列表
      let orgidlisttwo = []
      if (!hasChild) {
        orgidlisttwo = parlist.toString()
        setToken("organizationList", [nowselectid])
        // 让动态路由重新加载
        if (this.nowmenutype) {
          let accessRoutes = store.dispatch(
            "permission/generateRoutes"
          );
          accessRoutes.then(res => {
            // console.log(orgidlistone)
            // this.$router.push({ name: `${res[0].children[0].name}` });
            this.$router.push({ name: "selctBase" });
          })
        } else {
          this.$router.push({ name: "selctBase" });
        }
      } else {
        // console.log(orgidlistone)
        let orgliststring = []
        orgliststring = await this.getchildnodeidlist(nowselectid)
        orgidlisttwo = nowselectid + ',' + orgliststring
        setToken("organizationList", orgidlisttwo)
        // 让动态路由重新加载
        if (this.nowmenutype) {
          let accessRoutes = store.dispatch(
            "permission/generateRoutes"
          );
          // console.log(11)
          accessRoutes.then(res => {
            // this.$router.push({ name: `${res[0].children[0].name}` });
            this.$router.push({ name: "selctBase" });
          })
        } else {
          this.$router.push({ name: "selctBase" });
        }
      }
    },
    cascaderChange(e) {
      console.log(e)
    },
    // 选择公司时database
    getdataname(id) {
      // 获取databasename 并且存储session
      userService.getdatabasename(id).then(
        res => {
          let databaseName = res.data.databaseName
          setToken("databaseName", databaseName)
        }
      )
    },
    // 通过接口查子节点id
    async getchildnodeidlist(id) {
      let newArr = []
      await userService.getchildidlist(id).then(
        res => {
          newArr = res.data
          newArr.splice(0, 1)
          return newArr
        }
      )
      return newArr
    },
    // 循环过滤树形数组
    filterArrForKey(arr) {
      let newArr = []
      if (arr === []) {
        return
      }
      newArr = arr.map(item => {
        if (item.child.length > 0) {
          item = {
            ...item,
            child: this.filterArrForKey(
              item.child
            )
          }
        } else {
          delete item.child
        }
        return item
      })
      newArr = newArr.filter(item => item != null)
      return newArr
    },
    // ---侧边栏abcd选择，然而并没什么用
    changeActiveIdx(idx, item) {
      this.activeIdx = idx;
      this.search = item;
      // console.log(this.search);
    }
  }
};
</script>

<style scoped lang="scss">
@import "~@/styles/variables.scss";

@keyframes borderbg {
  from {
    border-radius: 0;
  }

  to {
    background-color: #fff;
    color: #333;
    border-radius: 20px;
  }
}

$slidebarWidth: 40px;

.choose-company {
  width: 100%;
  height: 100%;

  // background: linear-gradient(150.62deg, rgba(0, 203, 134, 1) 0%, rgba(31, 124, 135, 1) 100%, rgba(26, 135, 133, 1) 100%);
  .main-content {
    display: flex;
    width: 100%;
    height: calc(100% - #{$headerHeight});
    background-color: $appMainBgColor;
    // background: url("~@/assets/newbackground.png");
    // background-size: cover;
    // background-repeat: no-repeat;
    font-size: 14px;

    .el-scrollbar {
      background-color: #006988;

      //  border-radius: 20px;
      //  margin-top: 20px;
      //  margin-bottom: 20px;
      //  height: 95%;
      .slidebar {
        width: $slidebarWidth;
        height: 100%;

        // overflow-y: auto;
        .list {
          width: 100%;
          border-radius: 50px;

          .item {
            width: $slidebarWidth;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 16px;

            &:hover {
              animation-name: borderbg;
              animation-iteration-count: 1;
              animation-fill-mode: forwards;
              animation-duration: 0.5s;
            }
          }

          .active {
            font-weight: bold;
            background-color: #fff;
            color: #333;
          }
        }
      }
    }

    .main {
      width: 100%;

      .content {
        width: 100%;
        height: calc(100% - #{$footerHeight});
        display: flex;
        justify-content: center;
        align-items: center;
        // background-image: url("~@/assets/background.png");
        background-color: #003947;
        background-size: cover;
        background-repeat: no-repeat;

        .farm-list {
          width: 100%;
          height: 100%;
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          // justify-content: center;
          justify-content: space-around;
          padding: 40px;
          overflow-y: auto;

          .farm-item {
            width: 29%;
            height: 45%;
            position: relative;
            margin-bottom: 20px;
            margin-top: 20px;
            background: rgba(0, 110, 145, 0.4);
            border: 1px solid #b9d6de;
            color: #fff;
            padding: 15px;
            padding-bottom: 10px;
            cursor: pointer;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            transition: 0.5s;

            &:nth-child(4n) {
              margin-right: 0;
            }

            &:hover {
              transform: scale(1.1);
            }

            .pic {
              width: 100%;
              height: 80%;
              border: 1px solid #b9d6de;
              // background-image: url("~@/assets/index-bgc.png");
              background-image: url(https://img.js.design/assets/img/613074df79456d9eec79f371.jpg);
              background-color: #003947;
              background-size: cover;
              background-repeat: no-repeat;
            }

            .child-farm {
              position: absolute;
              right: 25px;
              bottom: 20px;
              width: 97px;
              height: 26px;
              background: linear-gradient(180deg, rgba(0, 193, 254, 1) 0%, rgba(41, 177, 220, 1) 57.22%, rgba(51, 207, 255, 1) 100%);
              box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.26);
              border-radius: 5px;
              color: rgba(255, 255, 255, 1);
              font-size: 16px;
              text-align: center;
              line-height: 26px;
            }

            .title {
              width: 100%;
              text-align: center;
              font-size: 0.8vw;
              margin: 5px 0;
            }

            .loc {
              width: 100%;
              display: flex;
              justify-content: center;
              font-size: 0.8vw;

              i {
                color: #56845b;
                font-size: 20px;
                margin-right: 5px;
              }
            }
          }
        }
      }
    }
  }

  .first-tankuang {
    width: 100%;
    height: 100%;
    background-color: rgba(228, 228, 228, 0.5);
    position: absolute;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;

    .org-list {
      width: 690px;
      height: 350px;
      background-color: rgba(0, 81, 81, 1);

      .org-title {
        height: 60px;
        border-bottom: #fff 1px solid;
        color: #fff;
        padding-left: 20px;
        font-size: 23px;
        display: flex;
        align-items: center;

        .sel-te {
          padding-left: 10px;
          line-height: 27px;
          height: 27px;
          border-left: #fff 4px solid;
          color: #fff;
          font-size: 23px;
        }
      }

      .search {
        width: 680px;
        height: 50px;
        margin-top: 40px;
        margin-bottom: 30px;
        display: flex;

        .search-input {
          outline: none;
          border: #fff 2px solid;
          font-size: 18px;
          width: 520px;
          margin-left: 45px;
          // margin-right: 35px;
          height: 40px;
        }

        .search-button {
          color: #fff;
          width: 80px;
          height: 40px;
          line-height: 40px;
          font-size: 18px;
          text-align: center;
          background-color: #7fd354;
          border-top-left-radius: 0px;
          border-top-right-radius: 2px;
          border-bottom-right-radius: 2px;
          border-bottom-left-radius: 0px;
          cursor: pointer;
        }
      }

      .company-list {
        width: 680px;
        height: 152px;
        padding-left: 10px;
        overflow: auto;
        margin-left: auto;
        margin-right: auto;
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
      }

      .sel-company {
        width: 270px;
        height: 46px;
        margin: 0px 30px 30px 30px;
        white-space: nowrap;
        cursor: pointer;
        background-color: transparent;
        border: #fff 1px solid;
        line-height: 46px;
        text-align: center;
        color: #fff;
      }

      .sel-company:hover {
        background-color: #fff;
        color: rgba(0, 81, 81, 1);
        ;
      }
    }
  }

  .three-tankuang {
    width: 100%;
    height: 100%;
    background-color: rgba(228, 228, 228, 0.5);
    position: absolute;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;

    .childcompany-list {
      border-radius: 9px;
      width: 590px;
      height: 250px;
      background-color: rgba(255, 255, 255, 1);
      border: 1px solid rgba(0, 0, 0, 1);

      .org-title {
        background-color: rgba(0, 110, 145, 1);
        border-top-left-radius: 9px;
        border-top-right-radius: 9px;
        border-bottom-right-radius: 0px;
        border-bottom-left-radius: 0px;
        height: 60px;
        // border-bottom: #fff 1px solid;
        color: #fff;
        padding-left: 20px;
        font-size: 23px;
        display: flex;
        align-items: center;

        .sel-te {
          padding-left: 10px;
          line-height: 27px;
          height: 27px;
          border-left: #fff 4px solid;
          color: #fff;
          font-size: 23px;
        }
      }

      .select-main {
        width: 500px;
        margin: 50px auto;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 9px;

        .far-sel {
          width: 300px;

          .el-cascader {
            width: 300px;
          }
        }

        .toindex-but {
          margin-left: 20px;
          width: 50px;
          height: 32px;
          cursor: pointer;
          color: #fff;
          line-height: 32px;
          white-space: nowrap;
          text-align: center;
          background-color: #7fd354;
          border-top-left-radius: 0px;
          border-top-right-radius: 2px;
          border-bottom-right-radius: 2px;
          border-bottom-left-radius: 0px;
        }

        .quxiao-but {
          margin-left: 10px;
          width: 50px;
          height: 32px;
          cursor: pointer;
          color: #fff;
          line-height: 32px;
          white-space: nowrap;
          text-align: center;
          background-color: #c6c938;
          border-top-left-radius: 0px;
          border-top-right-radius: 2px;
          border-bottom-right-radius: 2px;
          border-bottom-left-radius: 0px;
        }
      }
    }

  }
}</style>
<style lang="scss">.el-scrollbar__wrap {
  overflow-x: hidden;
}

.is-horizontal {
  display: none;
}</style>
